package auth

import (
	"context"
	"fmt"
	"time"

	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
	"golang.org/x/crypto/bcrypt"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	l.Infof("开始登录验证，用户名: %s", req.Username)

	// 查找用户
	user, err := l.svcCtx.UserModel.FindByUsername(req.Username)
	if err != nil {
		l.Errorf("用户查找失败，用户名: %s, 错误: %v", req.Username, err)
		return nil, fmt.Errorf("用户名或密码错误")
	}

	l.Infof("用户查找成功，用户ID: %d, 用户名: %s, 角色: %s", user.Id, user.Username, user.Role)

	// 验证密码
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password))
	if err != nil {
		l.Errorf("密码验证失败，用户名: %s, 错误: %v", req.Username, err)
		return nil, fmt.Errorf("用户名或密码错误")
	}

	l.Infof("密码验证成功，用户名: %s", req.Username)

	// 生成JWT令牌
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	claims := make(jwt.MapClaims)
	claims["exp"] = now + accessExpire
	claims["iat"] = now
	claims["id"] = user.Id
	claims["username"] = user.Username
	claims["role"] = user.Role
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
	if err != nil {
		l.Errorf("JWT令牌生成失败，用户名: %s, 错误: %v", req.Username, err)
		return nil, err
	}

	l.Infof("登录成功，用户名: %s, 角色: %s, 令牌已生成", user.Username, user.Role)

	return &types.LoginResp{
		Token: tokenString,
		UserInfo: types.User{
			Id:       user.Id,
			Username: user.Username,
			Name:     user.Name,
			Role:     user.Role,
			Phone:    user.Phone,
		},
	}, nil
}
